package amq.utils.thds;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

import amq.utils.JSFAgent;

public class JSFAgentSHBThd implements Runnable, MessageListener, ExceptionListener{
	public boolean isStop = false;	
	String brokerURI = null;	
	JSFAgent agent;
	String queueName = null;
	
	public JSFAgentSHBThd(String queueName, String bui, JSFAgent agent)
	{		
		this.brokerURI = bui;
		this.agent = agent;
		this.queueName = queueName;
	}

	@Override
	public void run() {
		try {
			System.out.printf("\t[Info] Opening Service Admin Queue(%s)...\n", queueName);
			// Create a ConnectionFactory
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerURI);

            // Create a Connection
            Connection connection = connectionFactory.createConnection();
            connection.start();

            connection.setExceptionListener(this);

            // Create a Session
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // Create the destination (Topic or Queue)
            Destination destination = session.createQueue(queueName);

            // Create a MessageConsumer from the Session to the Topic or Queue
            MessageConsumer consumer = session.createConsumer(destination);

            consumer.setMessageListener(this);
            while(!isStop)
            {
            	Thread.sleep(5000);
            }
           
            consumer.close();            
            session.close();
            connection.close();
        }
        catch (Exception e) {
            System.out.println("Caught: " + e);
            e.printStackTrace();
        }
		System.out.printf("\t[Info] Closing Service Admin Queue...Bye!\n");
		agent = null;
		
	}

	@Override
	public synchronized void onMessage(Message msg) {
		System.out.printf("\t[Info] Receive Message(%s):\n%s\n", queueName, msg);
		try
		{
			String info[] = ((TextMessage)msg).getText().split(":");
			if(info.length==2)
			{
				agent.srvhCallback(info[0], info[1], msg.getStringProperty("Topic"));
			}			
			else System.err.printf("\t[Error] Unknown msg='%s'!\n", ((TextMessage)msg).getText());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public void onException(JMSException expt) {
		System.err.printf("\t[Expt] Exception Message:\n%s\n", expt);		
	}
}
